//
//  MainViewController.m
//  waiMai
//
//  Created by LONG on 16/4/11.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MainViewController.h"
#import "DetailViewController.h"
#import "MainTableViewCell.h"
#import "MainDetailData.h"
#import "SearchViewController.h"
#import "ClassifyViewController.h"
@interface MainViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView *myTableView;
@property(nonatomic,strong) UITableView *leftTableView;
@property(nonatomic,strong) UITableView *rightTableView;
@property(nonatomic,strong) UIView *upBackview;
@property(nonatomic,strong) UIButton *footerButton;
@property(nonatomic,strong) UIScrollView *myScrollview;
@property(nonatomic,strong) NSArray *dataArray;
@property(nonatomic,strong) NSDictionary *itemDic;

@property(nonatomic,strong) NSMutableArray *modelArray;
@end

@implementation MainViewController{
    UIView          *_backView;
    UILabel         *_backlab;
    UINavigationBar *_navigationbar;
    UIButton     *_searchBut;
    UIPageControl   *_page;
    NSTimer         *_timer;
    BOOL            _Up;
    UIButton    *_rightBtn;


}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"";
    self.automaticallyAdjustsScrollViewInsets = YES;

    //假数据
    [self loadData];
    [self createModelsWithCount:10];
    
    
    [self initNavigationBar];
    [self change];
    [self searchview];
    [self myTableView];
    [self scrollViewCreate];
    [self headerViewCreate];
    [self leftRightTableView];
    
    NSArray *arr = @[@"you1(1)",@"bofang",@"you1(1)",@"bofang"];
    
    for (int i = 0; i<arr.count; i++) {
        UIImageView *image = [[UIImageView alloc]init];
        image.image = [UIImage imageNamed:arr[i]];
        image.frame = CGRectMake(WIDTH * i, 0, WIDTH, 100*MYWIDTH);
        [_myScrollview addSubview:image];
    }
    [self timerOn];
    
}

- (void)createModelsWithCount:(NSInteger)count
{
    if(_modelArray==nil)
    {
        _modelArray = [NSMutableArray array];
    }
    
    
    
    NSArray *iconImageNamesArray=@[@"1.5",
                                   @"2",
                                   @"3.5",
                                   @"4",
                                   @"4.5"];
    NSArray *nameArray = @[@"黄英",
                           @"莫顿",
                           @"王小姐",
                           @"SKHuang",
                           @"Kim"];
    
    NSArray *locationArray =@[@"广东省广州市白云区黄石东路3",
                              @"上海市闵行区吴宝路848号",
                              @"中国广东佛山",
                              @"天河公园",
                              @"广东省广州市白云区沙涌北涌南街79号",];
    
    NSArray *picImageNamesArray = @[ @"6",
                                     @"7",
                                     @"8",
                                     @"9",
                                     @"5",
                                     @"10",
                                     @"2",
                                     @"3",
                                     @"4"
                                     ];
    
    
    //根据传进来的数字创建对应的模型个数
    for(int i=0;i<count;i++)
    {
        int iconNameIndex = arc4random_uniform(4);
       

        MainDetailData *data = [MainDetailData new];
        data.image = picImageNamesArray[iconNameIndex];
        data.name=nameArray[iconNameIndex];
        data.fen=iconImageNamesArray[iconNameIndex];
        data.numer=picImageNamesArray[iconNameIndex];
        data.price=picImageNamesArray[iconNameIndex];
        data.juli = picImageNamesArray[iconNameIndex];
        data.favourable = locationArray[iconNameIndex];
        
        
        [self.modelArray  addObject:data];
        
    }
}

- (void)loadData {
    
    _dataArray = @[
                   @{@"title" : @"全部商家",
                     @"list" : @[@"Soldier", @"aaa0", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa1", @"aaa"]
                     },
                   @{@"title" : @"新店特惠",
                     @"list" : @[@"Soldier", @"aaa1", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa1", @"aaa"]
                     },
                   @{@"title" : @"连锁餐厅",
                     @"list" : @[@"Soldier", @"aaa2", @"aaa"]
                     },
                   @{@"title" : @"家常快餐",
                     @"list" : @[@"Soldier", @"aaa3", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa1", @"aaa"]
                     },
                   @{@"title" : @"地方菜",
                     @"list" : @[@"Soldier", @"aaa4", @"aaa"]
                     },
                   @{@"title" : @"特色小吃",
                     @"list" : @[@"Soldier", @"aaa5", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa1", @"aaa"]
                     },
                   @{@"title" : @"日韩料理",
                     @"list" : @[@"Soldier", @"aaa6", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa", @"aaa"]
                     }
                   ];
}

- (void)initNavigationBar{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    _navigationbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 85)];
    
    UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@""];
    
    [_navigationbar pushNavigationItem:item animated:NO];
    
    [self.view addSubview:_navigationbar];
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:18],
       NSForegroundColorAttributeName:UIColorFromRGB(0x444444)}];
    
    //nav底部线消失
    [_navigationbar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    _navigationbar.shadowImage = [[UIImage alloc] init];
    
    _navigationbar.translucent = NO;
    [_navigationbar setBarTintColor:UIColorFromRGB(MYColor)];
    
    
    _rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40, 23, 23, 23)];
    [_rightBtn setBackgroundImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(getMessage) forControlEvents:UIControlEventTouchUpInside];
    _rightBtn.hidden = YES;

    [_navigationbar addSubview:_rightBtn];
    
    
    
    //self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    //self.navigationController.interactivePopGestureRecognizer.delegate =(id)self;
    
    //定位View
    UIView *aview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH/2-100, 25, 200, 20)];
    [_navigationbar addSubview:aview];
    UIImageView *dwei = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    dwei.image = [UIImage imageNamed:@"icon_location"];
    [aview addSubview:dwei];
    UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(aview.frame.size.width-20, 0, 20, 20)];
    view.image = [UIImage imageNamed:@"iconfont-arrow"];
    [aview addSubview:view];
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(20, 0, 160, 20)];
    [aview addSubview:_backView];
    _backView.clipsToBounds = YES;
    
}
//搜索
- (void)getMessage{
    SearchViewController *search = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:search animated:YES];
}
- (UITableView *)myTableView{
    if (nil == _myTableView){
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 85, WIDTH, HEIGHT-86)];
        _myTableView.backgroundColor = [UIColor whiteColor];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        [_myTableView registerClass:[MainTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MainTableViewCell class])];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
        _myTableView.tableFooterView = view;
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}
//下拉菜单
- (void)leftRightTableView{
    if (_upBackview == nil) {
        _upBackview = [[UIView alloc]initWithFrame:CGRectMake(0, 79, WIDTH, 0)];
        _upBackview.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
        
        
        
        
        _footerButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 80, WIDTH, 0)];
        [_footerButton addTarget:self action:@selector(timeviewClick) forControlEvents:UIControlEventTouchUpInside];
        [_upBackview addSubview:_footerButton];
        
        [self.view addSubview:_upBackview];
    }
    if (_leftTableView == nil) {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH/2, 0)];
        _leftTableView.backgroundColor = UIColorFromRGB(0xefeff1);
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        [_upBackview addSubview:_leftTableView];
        
    }
    if (nil == _rightTableView){
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH/2-1, 0, WIDTH/2+1, 0)];
        _rightTableView.backgroundColor = [UIColor whiteColor];
        _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        [_upBackview addSubview:_rightTableView];
        
    }

}
- (void)timeviewClick{

    _Up = NO;
    
    [UIView animateWithDuration:0.5 animations:^{
        _footerButton.frame = CGRectMake(0, 50+30, WIDTH, 0);
        _leftTableView.frame = CGRectMake(0, 0, WIDTH/2, 0);
        _rightTableView.frame = CGRectMake(WIDTH/2-1, 0, WIDTH/2+1, 0);
        _upBackview.frame = CGRectMake(0, 79, WIDTH, 0);

        
    }];
    

}
- (UIScrollView *)scrollViewCreate{
    if (_myScrollview == nil) {
        
        _myScrollview = [[UIScrollView alloc]init];
        _myScrollview.frame = CGRectMake(0, 0, WIDTH, 100*MYWIDTH);
        _myScrollview.contentSize = CGSizeMake(WIDTH*4, 0);//设置scrollView的滚动范围（宽、高）
        _myScrollview.contentOffset = CGPointMake(0, 0);//设置scrollView要滚动的位置（x、y坐标）
        _myScrollview.bounces = NO;//是否有弹簧效果,默认是yes
        _myScrollview.showsHorizontalScrollIndicator = NO;
        _myScrollview.scrollEnabled = YES;//是否允许整页滚动
        _myScrollview.pagingEnabled = YES;
        _myScrollview.userInteractionEnabled = YES;
        _myScrollview.delegate = self;
        
        _page = [[UIPageControl alloc]init];
        _page.frame = CGRectMake(WIDTH/2 - 20, 100*MYWIDTH - 20, 40, 20);
        _page.numberOfPages = 4;
        _page.currentPage = 0;
        _page.userInteractionEnabled = YES;
        _page.pageIndicatorTintColor = [UIColor whiteColor];//未选中颜色
        _page.currentPageIndicatorTintColor = UIColorFromRGB(MYColor);//选中颜色
        
    }
    return _myScrollview;
}
- (UIButton *)searchview{
    if (_searchBut == nil) {
        _searchBut = [[UIButton alloc]init];
        _searchBut.frame = CGRectMake(8, 55,WIDTH-16, 25);
        [_searchBut setBackgroundColor:[UIColor whiteColor]];
        [_searchBut.layer setMasksToBounds:YES];
        [_searchBut.layer setCornerRadius:5.0];
        [_searchBut setTitle:@"搜索" forState:UIControlStateNormal];
        _searchBut.titleLabel.font = [UIFont systemFontOfSize:13];
        [_searchBut setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
         [_searchBut addTarget:self action:@selector(getMessage) forControlEvents:UIControlEventTouchUpInside];
        [_navigationbar addSubview:_searchBut];
    }
    return _searchBut;
}


- (void)headerViewCreate{
    UIImageView *headerimage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 85, WIDTH, 300*MYWIDTH+20)];
    headerimage.userInteractionEnabled = YES;
    [headerimage addSubview:_myScrollview];
    [headerimage addSubview:_page];
    
    //
    int totalloc=4;
    CGFloat appvieww=50*MYWIDTH;
    CGFloat appviewh=50*MYWIDTH;
    
    CGFloat margin=(WIDTH-totalloc*appvieww)/(totalloc+1);
    NSArray *dataarr = @[@"美食外卖",@"土豪馆",@"网站专送",@"鲜花蛋糕",@"水果素菜",@"便利店",@"生活服务",@"全部"];
    for (int i = 0; i<[dataarr count]; i++) {
        int row=i/totalloc;//行号
        int loc=i%totalloc;//列号
        CGFloat appviewx = margin+(margin+appvieww)*loc;
        CGFloat appviewy = margin+(margin+appviewh-40*MYWIDTH)*row+80*MYWIDTH;
        //
        UIImageView *butimage = [[UIImageView alloc]initWithFrame:CGRectMake(appviewx+10*MYWIDTH, appviewy-10*MYWIDTH, 30*MYWIDTH, 30*MYWIDTH)];
        butimage.image = [UIImage imageNamed:@"tabbar_item_home_selected"];
        [headerimage addSubview:butimage];
        //
        UIButton *but = [[UIButton alloc]initWithFrame:CGRectMake(appviewx, appviewy, appvieww, appviewh)];
        [but setTitle:dataarr[i] forState:UIControlStateNormal];
        but.titleLabel.lineBreakMode =  NSLineBreakByTruncatingTail;
        but.titleLabel.font = [UIFont systemFontOfSize:10];
        [but setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        [but addTarget:self action:@selector(Classbut:) forControlEvents:UIControlEventTouchUpInside];
        [headerimage addSubview:but];
        
    }
    UIView *xian1 = [[UIView alloc]initWithFrame:CGRectMake(0, 200*MYWIDTH, WIDTH, 10)];
    xian1.backgroundColor = UIColorFromRGB(0xefefef);
    [headerimage addSubview:xian1];

    UIImageView *imag = [[UIImageView alloc]initWithFrame:CGRectMake(0, 200*MYWIDTH+10, WIDTH, 100*MYWIDTH)];
    imag.image = [UIImage imageNamed:@"屏幕快照"];
    [headerimage addSubview:imag];

    UIView *xian2 = [[UIView alloc]initWithFrame:CGRectMake(0, 300*MYWIDTH+10, WIDTH, 10)];
    xian2.backgroundColor = UIColorFromRGB(0xefefef);
    [headerimage addSubview:xian2];

    
    _myTableView.tableHeaderView = headerimage;
    
   
}
- (void)Classbut:(UIButton *)but{
    ClassifyViewController *class = [[ClassifyViewController alloc]init];
    [self.navigationController pushViewController:class animated:YES];
}

//定位
- (void)change
{
    
    _backlab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 20)];
    _backlab.text = @"定位中...";
    _backlab.font = [UIFont systemFontOfSize:15];
    _backlab.textAlignment = NSTextAlignmentCenter;
    _backlab.textColor = [UIColor whiteColor];
    [_backView addSubview:_backlab];

}
#pragma mark 广告栏滚动
-(void)imgPlay{
    int i=(int)_page.currentPage;
    if (i==4-1) {
        i=-1;
    }
    i++;
    [_myScrollview setContentOffset:CGPointMake(i*WIDTH, 0) animated:YES];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self timerOff];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self timerOn];
}

-(void)timerOn{
    _timer=[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(imgPlay) userInfo:nil repeats:YES];
    //为了防止单线程的弊端，可以保证用户在使用其他控件的时候系统照样可以让定时器运转
    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
}

-(void)timerOff{
    [_timer invalidate];
    _timer=nil;
}

#pragma mark scrollview代理

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _page.currentPage=(_myScrollview.frame.size.width*0.5+_myScrollview.contentOffset.x)/_myScrollview.frame.size.width;
    if (_myTableView.contentOffset.y >100*MYWIDTH) {
        [UIView animateWithDuration:0.3 animations:^{

            _navigationbar.frame = CGRectMake(0, 0, WIDTH, 49);
            _myTableView.frame = CGRectMake(0, 49, WIDTH, HEIGHT-50);
            _searchBut.hidden = YES;
            _rightBtn.hidden = NO;
            
        }];
    }else if(_myTableView.contentOffset.y < 100*MYWIDTH){
        [UIView animateWithDuration:0.3 animations:^{
            _searchBut.hidden = NO;
            _rightBtn.hidden = YES;

            _navigationbar.frame = CGRectMake(0, 0, WIDTH, 85);
            _myTableView.frame = CGRectMake(0, 85, WIDTH, HEIGHT-86);

            
        }];
    }
    
}


    

#pragma mark tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView==_myTableView)
    {
        return 1;
    }
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView==_myTableView)
    {
        return self.modelArray.count;
    }else if(tableView==_leftTableView)
    {
        return _dataArray.count;
    }
    
    else if(tableView==_rightTableView)
    {
        return [[_itemDic objectForKey:@"list"] count];
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (tableView == self.myTableView) {
        
        Class currentClass = [MainTableViewCell class];
        MainTableViewCell *ceell = nil;
        MainDetailData *data = self.modelArray[indexPath.row];
        
        
        ceell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(currentClass)];
        
        
        ceell.data = data;
        
        return ceell;
    }else if (tableView == self.leftTableView) {
        
        cell.backgroundColor = UIColorFromRGB(0xefeff1);
        cell.textLabel.text = [_dataArray[indexPath.row] objectForKey:@"title"];
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        
    }else if (tableView == self.rightTableView){
        cell.textLabel.text = [_itemDic objectForKey:@"list"][indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:13];

    }
    return cell;
}

#pragma mark delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView==_myTableView)
    {
        
        return 130;
        
    }
    
    return 40;
    
}

//返回每一个组头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(tableView==_myTableView)
    {
        return 30;
    }
    
    return 0;
    
}

//返回组头部的那块View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(tableView==_myTableView)
    {
        UIView *view =[[UIView alloc]init];
        view.frame = CGRectMake(0, 0, tableView.frame.size.width, 30);
        view.backgroundColor = [UIColor whiteColor];
        
        NSArray *arr = @[@"分类",@"排序",@"筛选"];
        for (int i = 0; i< arr.count; i++) {
            UIButton *but = [[UIButton alloc]initWithFrame:CGRectMake(i*WIDTH/3, 1, WIDTH/3, 28)];
            [but setTitle:arr[i] forState:UIControlStateNormal];
            but.titleLabel.font = [UIFont systemFontOfSize:12];
            [but setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
            [but addTarget:self action:@selector(headerClick) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:but];
            if (i > 0) {
                UIView *xian = [[UIView alloc]initWithFrame:CGRectMake(i*WIDTH/3, 3, 1, 25)];
                xian.backgroundColor = UIColorFromRGB(0xefefef);
                [view addSubview:xian];
            }
            
        }
        
        UIView *xian1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
        xian1.backgroundColor = UIColorFromRGB(0xefefef);
        [view addSubview:xian1];
        
        UIView *xian2 = [[UIView alloc]initWithFrame:CGRectMake(0, 29, WIDTH, 1)];
        xian2.backgroundColor = UIColorFromRGB(0xefefef);
        [view addSubview:xian2];
        return view;
        
    }else{
        return nil;
    }
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView==_leftTableView)
    {

        _itemDic = [_dataArray objectAtIndex:indexPath.row];
        [_rightTableView reloadData];
    }
    
    else if(tableView == _rightTableView)
    {
        [_rightTableView deselectRowAtIndexPath:indexPath animated:NO];
        [self timeviewClick];
        
    }else if (tableView == _myTableView){
        DetailViewController *deta = [[DetailViewController alloc]init];
        deta.myTitle = @"买菜的";
        [self.navigationController pushViewController:deta animated:YES];
    }

}

- (void)headerClick{
    if (!_Up) {
        _Up = YES;
        
        [UIView animateWithDuration:0.5 animations:^{
            [self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            _upBackview.frame = CGRectMake(0, 79, WIDTH, HEIGHT-115);
            
            _footerButton.frame = CGRectMake(0, HEIGHT-215, WIDTH, 250);
            _leftTableView.frame = CGRectMake(0, 0, WIDTH/2, HEIGHT-215);
            _rightTableView.frame = CGRectMake(WIDTH/2-1, 0, WIDTH/2+1, HEIGHT-215);
        }];
    }else{
        [self timeviewClick];
    }
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIView animateWithDuration:0.5 animations:^{
        [self.navigationController setNavigationBarHidden:YES];
        
    }];
    self.tabBarController.tabBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [self timeviewClick];

    [super viewWillDisappear:animated];
}
@end
